package com.example.bysj_sb.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.bysj_sb.domain.User;
import com.example.bysj_sb.domain.authority.Actor;
import com.example.bysj_sb.domain.authority.ActorAssRole;
import com.example.bysj_sb.domain.authority.LoginResult;
import com.example.bysj_sb.domain.authority.Role;
import com.example.bysj_sb.service.ActorAssRoleService;
import com.example.bysj_sb.service.LogService;
import com.example.bysj_sb.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.TreeSet;

@Slf4j
@Controller
public class LoginController {
    @Autowired
    private LogService loginService;
    @Autowired
    private UserService userService;
    @Autowired
    private ActorAssRoleService actorAssRoleService;
    //返回json格式
    @ResponseBody
    //该方法根据username和password返回及用户的身份和拥有的角色
    @GetMapping("/login.ctl")
        public JSONObject find(@RequestBody User user) {
        JSONObject message = new JSONObject();
        //根据user对象获取actor对象
        Actor currentActor = userService.login(user);
        if (currentActor == null) {
            message.put("message", "用户名或密码不匹配 !");
            return message;
        } else {
            //获得某Actor对象关联的所有ActorAssRole对象
            Collection<ActorAssRole> actorAssRoleCollection =
                    actorAssRoleService.findByActorId(currentActor);
            //根据ActorAssRole对象获得对应的Role对象
            Collection<Role> roles = new TreeSet<>();
            for (ActorAssRole actorAssRole : actorAssRoleCollection) {
                Role role = actorAssRole.getRole();
                roles.add(role);
            }
            message.put("actor",currentActor);
            message.put("roles" ,roles);
            return message;
        }
    }
    //该方法返回登录界面
    @PostMapping(value = "/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        System.out.println(username + " login()");
        //LoginResult类用来判断登录结果
        LoginResult loginResult = loginService.login(username,password);
        if(loginResult.isLogin()){
            System.out.println("登陆成功！");
        return "index";
        } else {
            throw new RuntimeException("登录失败：" + loginResult.getResult());
        }
    }
}
